<template>
  <view class="pageContent" >
    <!-- <view class="memberTitle">第1步：登记信息</view> -->
    <view class="memberMain">
        <view class="memberMaTi">选择成员身份</view>
        <view>
          <view class="memberType" :class="index==headIndex ? 'select' : ''" v-for="(item,index) in headList" :key="index" @click="selectHead(index)">
            {{item.roleName || '成员身份'}}
          </view>
          <view class="memberType" v-if="0">
            {{'成员身份'}}
          </view>
        </view>
        <view class="memberItem">
          <text class="memberItSt">*</text>
          <view class="memberItTi">身份证号</view>
          <view class="memberRight">
            <input class="memberItIn" type="idcard" placeholder-class="inputPlaceHold" v-model="formData.idCardNumber" :placeholder="placeholderId" maxlength="18" @input="inputChange" :disabled="updateFlag" id="idCardNumber"/>
          </view>
        </view>
        <view class="memberItem">
          <text class="memberItSt">*</text>
          <view class="memberItTi">成员真名</view>
          <view class="memberRight">
            <input class="memberItIn" placeholder-class="inputPlaceHold" v-model="formData.name" :placeholder="placeholder" :disabled="disabledFlag"/>
          </view>
        </view>
        <view class="memberItem">
          <text class="memberItSt">*</text>
          <view class="memberItTi">性<text style="color: #fff;">籍贯</text>别</view>
          <view class="memberRight">
            <view class="perType" :class="index==perIndex ? 'select' : ''"
            v-for="(item,index) in perList" :key="index" @click="selectPer(index)">
              {{item.name}}
            </view>
          </view>
        </view>
        <view class="memberItem">
          <text class="memberItSt">*</text>
          <view class="memberItTi">出生年月</view>
          <picker class="comePicRight" mode="date" :value="date" @change="choose" id="deliverTime" v-if="!disabledFlag">
            <input class="memberItIn" placeholder-class="inputPlaceHold" v-model="formData.date" :placeholder="placeholderAd" disabled="true"/>
            <image class="comePicLim" :src="localImages +'/date.png'" mode="scaleToFill"/>
          </picker>
          <view class="comePicRight" v-if="disabledFlag">
            <input class="memberItIn" placeholder-class="inputPlaceHold" v-model="date" :placeholder="placeholderAd" disabled="true"/>
          </view>
         <!-- <view class="memberRight">
            <input class="memberItIn" placeholder-class="inputPlaceHold" v-model="formData.date" :placeholder="placeholderAd" disabled="true"/>
            <picker class="comePicRight" mode="date" :value="date" @change="choose" id="deliverTime" v-if="!disabledFlag">
              <image class="comePicLim" :src="localImages +'/date.png'" @click="selectDate"/>
            </picker>
          </view> -->
        </view>

        <view class="memberItem">
          <text class="memberItSt">*</text>
          <view class="memberItTi">手机号码</view>
          <view class="memberRight">
            <input class="memberItIn" type="number" placeholder-class="inputPlaceHold" v-model="formData.phone" :placeholder="placeholderPh" maxlength="11" @input="inputChange" :disabled="disabledFlag" id="phone"/>
          </view>
        </view>
        <view class="memberItem">
          <text class="memberItSt empty">*</text>
          <view class="memberItTi">上传证件</view>
          <view class="memberUpload">
            <view @click="imagePhoto" data-type="idCardFrontUrl">
              <image class="memberUpTrueIc" v-if="!idCardFrontUrl" :src="localImages +'/dateTrue.png'"/>
              <image class="memberUpTrueIc" v-if="idCardFrontUrl" :src="idCardFrontUrl"/>
            </view>
            <view @click="imagePhoto" data-type="idCardBackUrl">
              <image class="memberUpTrueIc" v-if="!idCardBackUrl" :src="localImages +'/dateFalse.png'"/>
              <image class="memberUpTrueIc" v-if="idCardBackUrl" :src="idCardBackUrl"/>
            </view>
          </view>
        </view>
        <view class="memberItem" v-if="0">
          <text class="memberItSt empty">*</text>
          <view class="memberItTi">上传生活<text>\n&nbsp;&nbsp;&nbsp;照片</text></view>
          <view class="memberUpload">
            <view @click="imagePhoto" data-type="facePictureUrl">
              <view class="memberUpMain" v-if="!facePictureUrl">
                <image class="memberUpMainIm" :src="images +'/facePictureBac.png'"/>
                <image class="memberUpMainIc centerAbs" :src="images +'/facePictureIc.png'"/>
                <view class="centerAbs memberUpMainTe">上传生活照片</view>
              </view>
              <image class="memberUpTrueIc " v-if="facePictureUrl" :src="facePictureUrl"/>
            </view>
          </view>
        </view>
        <!-- <view class="memberItem" v-if="1"> -->
        <view class="memberItem" v-if="headIndex==0 && userMsg.roleId==16">
          <text class="memberItSt empty">*</text>
          <view class="memberItTi">租赁合同</view>
          <view class="memberUploadLea">
            <view class="memberUpLeaMa" @click="imagePhoto" data-type="leaseContractOneUrl">
              <image class="memberUpLea" v-if="!leaseContractOneUrl" :src="images +'/lease1.png'"/>
              <image class="memberUpLea" v-if="leaseContractOneUrl" :src="leaseContractOneUrl"/>
            </view>
            <view class="memberUpLeaMa" @click="imagePhoto" data-type="leaseContractTwoUrl">
              <image class="memberUpLea" v-if="!leaseContractTwoUrl" :src="images +'/lease2.png'"/>
              <image class="memberUpLea" v-if="leaseContractTwoUrl" :src="leaseContractTwoUrl"/>
            </view>
           <view class="memberUpLeaMa" @click="imagePhoto" data-type="leaseContractThreeUrl">
              <image class="memberUpLea" v-if="!leaseContractThreeUrl" :src="images +'/lease3.png'"/>
              <image class="memberUpLea" v-if="leaseContractThreeUrl" :src="leaseContractThreeUrl"/>
            </view>
            <view class="memberUpLeaMa" @click="imagePhoto" data-type="leaseContractFourUrl">
              <image class="memberUpLea" v-if="!leaseContractFourUrl" :src="images +'/lease4.png'"/>
              <image class="memberUpLea" v-if="leaseContractFourUrl" :src="leaseContractFourUrl"/>
            </view>
          </view>
        </view>
        <view class="memberItem">
          <text class="memberItSt empty">*</text>
          <view class="memberItTi">门禁期限</view>
          <picker class="comePicRight" mode="date" :value="dateLim" @change="chooseLim">
            <input class="memberItIn" placeholder-class="inputPlaceHold" v-model="dateLim" :placeholder="placeholder5" disabled="true"/>
            <image class="comePicLim" :src="localImages +'/date.png'" mode="scaleToFill"/>
          </picker>
        </view>
        <view class="memberItem">
          <text class="memberItSt empty">*</text>
          <view class="memberItTi">留言：</view>
          <view class="memberRight">
            <input class="memberItIn" placeholder-class="inputPlaceHold" v-model="formData.applyReason" placeholder="请填写留言" maxlength="30"/>
          </view>
        </view>
        <button class="btOne" @click="commitTamp" :class="headIndex==-1 ? 'btDefault' : ''">提交</button>
    </view>

  </view>
</template>

<script>
import { mapState } from 'vuex'
import config from '../../../../static/config.js'
import util from '../../../../static/utils/util.js'
export default {
  data () {
    return {
      images: config.images,
      localImages: config.localImages,
      password: '',
      headList: [
          { value: 0, name: '租户',},
          { value: 2, name: '父母',},
          { value: 3, name: '小孩',},
          { value: 3, name: '朋友',},
          { value: 3, name: '朋友',},
      ],
      headIndex:-1,
      perList: [
          { value: 0, name: '男',},
          { value: 1, name: '女',},
      ],
      perIndex:0,
      formData:{
        roleId:"",
        name:"",
        idCardNumber:"",
        sex:0,
        date:"",
        phone:"",
        dateLim:"",
      },
      idCardFrontUrl:'',
      idCardBackUrl:'',
      facePictureUrl:'',
      leaseContractOneUrl:'',
      leaseContractTwoUrl:'',
      leaseContractThreeUrl:'',
      leaseContractFourUrl:'',
      placeholder:'请填写身份证上的真实姓名',
      placeholderAd:'请选择出生年月',
      placeholderId:'请填写有效身份证号码',
      placeholderPh:'请填写手机号',
      placeholder5:'请选择门禁失效日期',
      date: '',
      dateLim: '',
      previous: '',
      disabledFlag:false,//禁止修改字段的标记
      userMsg: '',
      updateFlag:false,//修改成员的标记
    }
  },
  computed: {
    ...mapState({
      myInfo: state => state.user.myInfo
    })
  },
  onLoad(options) {
    var title='添加成员'
    var userMsg = wx.getStorageSync('userMsg');
    this.userMsg=userMsg;
    //修改成员
    if(options.json){
      var title='修改成员'
      this.updateFlag=true;
      var param=JSON.parse(options.json)
      console.warn('param',param)
      Object.assign(this.formData,param)
      //添加id
      this.formData['id']=param.ownerId
      this.updateParam(param);
      this.headListGet().then(()=>{
        //判断成员身份
        this.headList.forEach((item,index)=>{
          if(item.roleId==param.roleId) {
            this.headIndex=index;
            console.warn('this.headIndex',this.headIndex,index)
          }
        })
      });
      this.modifyParam(param);
    }else {
      this.updateFlag=false;
      //添加申请人的id参数
      var room = wx.getStorageSync('room');
      var param={
        roomIdNow:room.roomId,
        projectId:room.projectId,
      }
      Object.assign(this.formData,param)
      this.headListGet().then(()=>{
        this.selectHead(0) //默认选择第一个选项
      });
    }
    wx.setNavigationBarTitle({title: title})

  },
  onShow(){
    util.socketTest();
  },
  onUnload(){
    this.reset()
  },
  methods: {
    inputChange(e) {
      var e=e.mp
      console.warn(e)
      var value = e.detail.value;
      var key = e.currentTarget.id;
      // if(this.updateFlag){ //修改直接返回
      //   return;
      // }
      if(key=='idCardNumber') {
        //查询系统是否有身份信息
        if(value.length==18) {
          var params={
            idCardNumber:value,
          }
          this.ownerInfo(params,true).then((res)=>{
            if(res.param){
              var param=res.param;
              this.updateParam(param);
              this.disabledFlag=true;
            }else {
              this.disabledFlag=false;
            }
          });
        }
        //清空之前回填的信息，防止通过手机号修改原有用户的信息
        if(value.length==17 && this.disabledFlag) {
          this.reset();
          this.formData.idCardNumber=value;
        }
        else {
          this.disabledFlag=false;
          console.warn('disabledFlag',this.disabledFlag)
        }
      }
      if(key=='phone') {
        //查询系统是否有手机号
        if(value.length==11) {
          var params={
            telephone:value,
          }
          this.ownerInfo(params).then((res)=>{
            if(res.param){
              wx.showToast({
                title: '当前手机号已经存在，请重新输入',
                icon: 'none',
                duration: 1500,
              })
              this.formData.phone=""
            }
          });
        }
      }
    },
    chooseLim(e) {
      var e=e.mp
      console.warn('chooseLim',e)
      this.dateLim = e.detail.value
      this.formData.dateLim = e.detail.value
    },
    choose(e) {
      var e=e.mp
      console.warn('choose',e)
      this.date = e.detail.value
      this.formData.date = e.detail.value
    },
    selectDate(){
      console.warn("selectDate")
    },
    selectHead(index){
      this.headIndex=index;
      this.formData.roleId=this.headList[index].roleId;
    },
    selectPer(index){
      if(this.disabledFlag) return;
      this.perIndex=index;
      this.formData.sex=this.perList[index].value;
    },
    headListGet(){
      return new Promise((resolve,reject)=>{
        var params={}
        util.wxRequestPro('/UserServer/owner/info/roleName',params)
        .then((res)=>{
          var param=res.param;
          //租客不显示租客
          if(this.userMsg.roleId==17){
            param.shift();
          }
          this.headList=param
          resolve()
        })
      })
    },
    ownerInfo(params,showToast=true){
      return new Promise((resolve,reject)=>{
        util.wxRequestPro('/UserServer/owner/info/ownerInfo',params,"GET",showToast)
        .then((res)=>{
          resolve(res)
        }).catch((res)=>{
          reject()
        })
      })
    },
    //修改用户，显示图片信息
    modifyParam(param){
      if(param.idCardFrontUrl){
        this.formData.idCardFrontUrl=param.idCardFrontUrl;
        this.idCardFrontUrl=config.IMAGE_APIHOST+param.idCardFrontUrl;
      }
      if(param.idCardBackUrl){
        this.formData.idCardBackUrl=param.idCardBackUrl;
        this.idCardBackUrl=config.IMAGE_APIHOST+param.idCardBackUrl;
      }
      if(param.facePictureUrl){
        this.formData.facePictureUrl=param.facePictureUrl;
        this.facePictureUrl=config.IMAGE_APIHOST+param.facePictureUrl;
      }
      if(param.leaseContractOneUrl){
        this.formData.leaseContractOneUrl=param.leaseContractOneUrl;
        this.leaseContractOneUrl=config.IMAGE_APIHOST+param.leaseContractOneUrl;
      }
      if(param.leaseContractTwoUrl){
        this.formData.leaseContractTwoUrl=param.leaseContractTwoUrl;
        this.leaseContractTwoUrl=config.IMAGE_APIHOST+param.leaseContractTwoUrl;
      }
      if(param.leaseContractThreeUrl){
        this.formData.leaseContractThreeUrl=param.leaseContractThreeUrl;
        this.leaseContractThreeUrl=config.IMAGE_APIHOST+param.leaseContractThreeUrl;
      }
      if(param.leaseContractFourUrl){
        this.formData.leaseContractFourUrl=param.leaseContractFourUrl;
        this.leaseContractFourUrl=config.IMAGE_APIHOST+param.leaseContractFourUrl;
      }
    },
    //回显用户基本信息
    updateParam(param){
      this.formData.phone=param.telephone;
      this.formData.name=param.name;
      this.formData.date=param.birthday;
      this.date=param.birthday;
      this.dateLim=param.expireDate || ''; //不存在就传空
      //判断性别
      this.perList.forEach((item,index)=>{
        if(item.value==param.sex) {
          this.perIndex=index;
          console.warn('this.perIndex',this.perIndex,index)
        }
      })
    },
    //图片上传
    imagePhoto(e){
      var e=e.mp;
      var type = e.currentTarget.dataset.type;
      var self = this;
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success (res) {
          const tempFilePaths = res.tempFilePaths
          var src = res.tempFilePaths[0];
          util.uploadFile(src).then((res)=>{
            var param=res;
            //测试环境取服务器地址
            // if(config.isRelease){
            //   var url=param.url
            // }else {
            //   //本地环境取本地地址
            //   var url=config.IMAGE_APIHOST
            // }
            var urlPath=param.url+param.filePath;
            if(type=='idCardFrontUrl') {
              self.idCardFrontUrl=urlPath;
              self.formData[type]=param.filePath;
            }
            else if(type=='idCardBackUrl') {
              self.idCardBackUrl=urlPath;
              self.formData[type]=param.filePath;
            }
            else if(type=='facePictureUrl') {
              self.facePictureUrl=urlPath;
              self.formData[type]=param.filePath;
            }
            else if(type=='leaseContractOneUrl') {
              self.leaseContractOneUrl=urlPath;
              self.formData[type]=param.filePath;
            }
            else if(type=='leaseContractTwoUrl') {
              self.leaseContractTwoUrl=urlPath;
              self.formData[type]=param.filePath;
            }
            else if(type=='leaseContractThreeUrl') {
              self.leaseContractThreeUrl=urlPath;
              self.formData[type]=param.filePath;
            }
            else if(type=='leaseContractFourUrl') {
              self.leaseContractFourUrl=urlPath;
              self.formData[type]=param.filePath;
            }
          })
        }
      })
    },

    commitTamp() {
      util.tottleOne(()=>{
        this.submit()
        // if(this.updateFlag) {
        //   this.updateOwner()
        // }else {
        //   this.submit()
        // }
      })
    },
    updateOwner(){
      var params=this.formData;
      params['expireDate']=this.dateLim;
      params['birthday']=params.date;
      params['telephone']=params.phone;
      console.warn('params',params)
      util.wxRequestPro('/UserServer/owner/info/ownerInfo',params,"PUT")
      .then((res)=>{
        wx.showToast({
          title: '修改成功',
          icon: 'none'
        })
        setTimeout(()=>{wx.navigateBack({delta:1})},500)
      }).catch((res)=>{
        console.warn('ownerRoomList',res)
        wx.showToast({
          title: res.status || res.statusInfo || res.error,
          icon: 'none'
        })
      })
    },
    submit(){
      var status = this.validation() || false;
      if(status) {
        //获取业主该手机号绑定的房屋列表
        var params=this.formData;
        params['expireDate']=this.dateLim;
        params['birthday']=params.date;
        params['telephone']=params.phone;
        // var params={"name":"aa11","idCardNumber":"430406202101011031","telephone":"13012345681","sex":1,"birthday":"1993-7","roomIdNow":"16","projectId":"1","expireDate":"2088-12-31","roleId":"17"}
        console.warn('params',params)
        var method="POST"
        if(this.updateFlag) {
          method="PUT"
        }
        util.wxRequestPro('/UserServer/owner/info/ownerInfo',params,method)
        .then((res)=>{
          var title="添加成功"
          if(this.updateFlag) {
            title="修改成功"
          }
          wx.showToast({
            title: title,
            icon: 'none'
          })
          setTimeout(()=>{wx.navigateBack({delta:1})},500)
        }).catch((res)=>{
          console.warn('ownerRoomList',res)
          wx.showToast({
            title: res.status || res.statusInfo || res.error,
            icon: 'none'
          })
        })
      }
    },
    reset(){
      this.formData={
        roleId:"",
        name:"",
        idCardNumber:"",
        sex:0,
        date:"",
        phone:"",
        dateLim:"",
      };
      this.headIndex=-1;
      this.perIndex=0;
      this.date="";
      this.dateLim="";
      this.disabledFlag=false;
      this.idCardFrontUrl=''
      this.idCardBackUrl=''
      this.facePictureUrl=''
      this.leaseContractOneUrl=''
      this.leaseContractTwoUrl=''
      this.leaseContractThreeUrl=''
      this.leaseContractFourUrl=''
    },
    validation() {
      if (this.formData.roleId === '') {
        wx.showToast({
            title: "请选择成员身份",
            icon: 'none'
        });
        return false;
      }
      if (this.formData.idCardNumber == '') {
        wx.showToast({
            title: this.placeholderId,
            icon: 'none'
        });
        return false;
      }
      if (this.formData.name == '') {
        wx.showToast({
            title: this.placeholder,
            icon: 'none'
        });
        return false;
      }
      else {
        var value = util.checkIDCardNum(this.formData.idCardNumber.trim());
        if (!value) {
            wx.showToast({ title: "请填写正确的身份证号码", icon: 'none' });
            return false;
        }
      }
      if (this.formData.date == '') {
        wx.showToast({
            title: this.placeholderAd,
            icon: 'none'
        });
        return false;
      }
      if (this.formData.phone == '') {
        wx.showToast({
            title: this.placeholderPh,
            icon: 'none'
        });
        return false;
      }
      else {
        var value = util.checkPhoneNum(this.formData.phone.trim());
        if (!value) {
            wx.showToast({ title: "请填写正确的手机号码", icon: 'none' });
            return false;
        }
      }
      return true;
    }

  }
}
</script>

<style lang="stylus" scoped>
.pageContent{
  background $background
  padding: 20rpx 0rpx 0rpx 0rpx;
}
.memberTitle{
  font-size: 30rpx;
  font-weight: bold;
  color: #333333;
  line-height: 42rpx;
  padding: 30rpx 0rpx 20rpx 30rpx;
}
.memberMain{
  background-color #FFFFFF
  padding: 30rpx 30rpx 20rpx 30rpx;
}
.memberMaTi{
  color: #333333;
  line-height: 42rpx;
  font-size: 30rpx;
  padding: 0rpx 0rpx 10rpx 0rpx;
}
.memberType{
  display inline-block
  width: 150rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 6rpx;
  text-align center
  border: 1rpx solid #E7E7E7;
}
.memberType.select{
  background-color #7A71FF
  color: #FFFFFF;
}
.memberType + .memberType{
  margin-left 30rpx
}
.memberType:nth-child(n+5){
  margin-top 20rpx
  // color red
}
.memberType:nth-child(4n+1){
  margin-left 0rpx
  // color green
}

.memberItem{
  display flex
  align-items center
  // line-height 90rpx
  font-size: 30rpx;
  // border: 1rpx solid #999999;
}
.memberItSt{
  color: #FF6E5D;
}
.memberItSt.empty{
  color #FFFFFF
}
.memberItTi{
  width 150rpx;
  color: #333333;
  margin-right 36rpx;
  text-align:justify;
  white-space nowrap
  // border: 1rpx solid coral;
}
.memberRight{
  display flex
  height 90rpx
  width 100%
  align-items center
  border-bottom: 1rpx solid #E7E7E7;
  // border: 1rpx solid darkgreen;
}

.memberItIn{
  width 88%
  // border: 1rpx solid #E7E7E7;
}
.memberItIc{
  width: 35rpx;
  height: 30rpx;
  // background: #237DE4;
  margin: 0rpx 10rpx 0rpx 20rpx;
}
.perType{
  display inline-block
  width: 90rpx;
  // height: 45rpx;
  line-height: 45rpx;
  border-radius: 4rpx;
  text-align center
  margin-right 20rpx
  color #70B7FF
  background #F2F8FF
  border: 1rpx solid #B8DCFF;
}
.perType.select{
  background-color $primary
  color: #FFFFFF;
}

.memberUpload{
  display flex
  width 100%
  justify-content space-between
  align-items center
  padding: 20rpx 0rpx 20rpx 0rpx;
  border-bottom: 1rpx solid #E7E7E7;
}
.memberUpTrueIc{
  width: 230rpx;
  height: 152rpx;
  // border: 1rpx solid aqua;
}
.memberUpMain{
  position relative
  width: 230rpx;
  height: 152rpx;
  // border: 1rpx solid aqua;
}
.memberUpMainIm{
  position absolute
  width: 230rpx;
  height: 152rpx;
}
.memberUpMainIc{
  position absolute
  width: 44rpx;
  height: 36rpx;
}
.memberUpMainTe{
  position absolute
  height: 36rpx;
  line-height 36rpx;
  font-size 20rpx;
  color #1086FF;
  margin-top 50rpx
  white-space nowrap
}
.memberUploadLea{
  display flex
  width 100%
  padding: 20rpx 0rpx 20rpx 0rpx;
  border-bottom: 1rpx solid #E7E7E7;
  // border: 1rpx solid aqua;
}
.memberUpLeaMa{
  display inline-block
  width: 124rpx;
  height: 84rpx;
}
.memberUpLeaMa:nth-child(n+2){
  margin-left 8rpx;
}
.memberUpLea{
  display inline-block
  width: 124rpx;
  height: 84rpx;
}
.comePicRight{
  position relative
  display flex
  height 90rpx
  width 100%
  align-items center
  border-bottom: 1rpx solid #E7E7E7;
}
.comePicLim{
  position absolute
  right 0rpx
  top 26rpx
  width: 35rpx;
  height: 30rpx;
  // background: #237DE4;
  margin: 0rpx 0rpx 0rpx 0rpx;
}
.btOne{
  margin: 40rpx 0rpx 0rpx 0rpx;
}
.btDefault{
  opacity 0.6
}
</style>
